package com.example.studytest.Util;

import com.csvreader.CsvWriter;
import com.example.studytest.Entity.Test4.Record_score_info;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CreateSheetUtil {

    /*@author: xiehuan
     * @param: sheetName: 表名
     * @param: heads: 表头
     * @param：dataList: 数据
     * @return：XSSFWorkbook表格
     * */
    public static XSSFWorkbook createXSSFWorkbook(String sheetName,
                                                  String[] heads,
                                                  List<Object> dataList) {

        //创建工作薄
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
        //创建工作表
        XSSFSheet sheet = xssfWorkbook.createSheet();
        xssfWorkbook.setSheetName(0, sheetName);
        //创建表头
        XSSFRow head = sheet.createRow(0);
        for (int i = 0; i < heads.length; i++) {
            XSSFCell cell = head.createCell(i);
            cell.setCellValue(heads[i]);
        }

        //具体数据写入
        int cell = 1;
        for (Object item : dataList) {
            Row row = sheet.createRow(cell);//从第二行开始保存数据
            List<Object> val_list = ObjectToListUtil.goThroughObj(item);
            for (int j = 0; j < heads.length; j++) {
                row.createCell(j).setCellValue(String.valueOf(val_list.get(j)));
            }
            cell++;
        }

        return xssfWorkbook;
    }

    public static <T> File createCsv(String csvName,
                                          String[] heads,
                                          List<T> dataList) throws IOException {
        File file = File.createTempFile("data", ".csv");
        CsvWriter csvWriter = new CsvWriter(file.getCanonicalPath(), ',', Charset.forName("UTF-8"));

        //写表头
        csvWriter.writeRecord(heads);

        Iterator<T> iterator = dataList.iterator();
        //具体数据写入
        while (iterator.hasNext()) {
            T next = (T) iterator.next();
            String[] csvContent = ObjectToListUtil.goThroughObjToStr(next);
            csvWriter.writeRecord(csvContent);
        }
        csvWriter.close();
        return file;
    }

    public static <T> File createCsv2(String csvName,
                                     String[] heads,
                                     List<Map<String,Object>> dataList) throws IOException {
        File file = File.createTempFile("data", ".csv");
        CsvWriter csvWriter = new CsvWriter(file.getCanonicalPath(), ',', Charset.forName("UTF-8"));

        //写表头
        csvWriter.writeRecord(heads);

        Iterator<Map<String,Object>> iterator = dataList.iterator();
        //具体数据写入
        while (iterator.hasNext()) {
            Map<String,Object> next = (Map<String,Object>) iterator.next();//迭代每一条数据
//            System.out.println(next.keySet());
//            String[] csvContent = ObjectToListUtil.goThroughObjToStr(next);
            List<String> strList = new ArrayList<>();

//            String[] csvContent=new String[20];
            for (String key: next.keySet()){
                if (next.get(key)==null){
                    strList.add("null");
                }
                else {
                    strList.add(next.get(key).toString());
                }

            }
            String[] csvContent=strList.toArray(new String[strList.size()]);
            csvWriter.writeRecord(csvContent);
        }
        csvWriter.close();
        return file;
    }


    public static void exportExcel(String sheetName, List<String> column, List<Map<String,Object>> data, HttpServletRequest request, HttpServletResponse response){
        //创建工作薄
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        //创建sheet
        HSSFSheet sheet = hssfWorkbook.createSheet(sheetName);
        // 表头
        HSSFRow headRow = sheet.createRow(0);
        for (int i = 0; i < column.size(); i++){
            headRow.createCell(i).setCellValue(column.get(i));
        }

        for (int i = 0; i < data.size(); i++) {
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            for (int x = 0; x < column.size(); x++) {
                dataRow.createCell(x).setCellValue(data.get(i).get(column.get(x))==null?"":data.get(i).get(column.get(x)).toString());
            }
        }

        response.setContentType("application/vnd.ms-excel");

        try {
            //获取浏览器名称
            String agent=request.getHeader("user-agent");
            String filename=sheetName+".xls";
            //不同浏览器需要对文件名做特殊处理
            if (agent.contains("Firefox")) { // 火狐浏览器
                filename = "=?UTF-8?B?"
                        + new BASE64Encoder().encode(filename.getBytes("utf-8"))
                        + "?=";
                filename = filename.replaceAll("\r\n", "");
            } else { // IE及其他浏览器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+"," ");
            }
            //推送浏览器
            response.setHeader("Content-Disposition","attachment;filename="+filename);
            hssfWorkbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
